<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use App\Models\video\BroadcasterModel;
use App\Models\video\BroadcasterRelationModel;
use App\Models\video\CommentModel;
use App\Models\video\OperateModeModel;
use App\Models\video\PlayClassModel;
use App\Models\video\PlayedRecordModel;
use App\Models\video\PlayListModel;
use App\Models\video\ReplyModel;
use App\Models\video\SubscriptionModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\VideoUserModel;
use App\Models\video\VodVideoModel;
use Illuminate\Http\Request;

class UserController extends BaseController
{
    public function __construct(Request $request)
    {
//        $this->noCheckTokenAction = ['getMyPlayClassList', 'getPlayVideoList']; //不校验openid
        parent::__construct($request);
    }

    //获取登录用户基本信息
    public function getUserInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $field = "id,nickname,mobile,avatar,openid,balance,amount,register_time,user_type,subscribe_count,level_time";
        $data = VideoUserModel::getFields($field, ["id" => $request->userLoginData["id"]], true);
        if(!empty($data)) {
            $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
            if ($data["userType"] == '1' && $settingData["operateMode"] == '1') {
                $count = BroadcasterModel::query()->from(BroadcasterModel::query()->getModel()->getTable()." as b")
                    ->leftJoin(BroadcasterRelationModel::query()->getModel()->getTable()." as br", "b.id", "=", "br.broadcaster_id")
                    ->select("br.user_id")
                    ->where(["b.status" => 1, "b.mall_id" => request()->mallData["id"], "br.user_id" => $data["id"]])
                    ->count();
                $data["userType"] = $count ? 1 : 0;
            }
            $data["memberStatus"] = 0;
            if ($data["levelTime"] > date("Y-m-d", time())) {
                $data["memberStatus"] = 1;
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 添加播放列表
    public function addPlayClass(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->name){
            return $this->return_result(ErrorCode::code("params_not_exist", "名称"));
        }
        $id = PlayClassModel::toAdd(["user_id" => $request->userLoginData["id"], "name" => $request->name], true);
        $this->returnData["data"] = ["id" => $id];
        return $this->return_result($this->returnData);
    }

    // 删除播放列表
    public function delPlayClass(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "分类列表ID"));
        }
        PlayClassModel::delById($request->id);
        return $this->return_result($this->returnData);
    }

    // 我的播放分类列表
    public function getMyPlayClassList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $userId = $request->userLoginData["id"];
        $playClassData = PlayClassModel::getFields("id,name,num", ["user_id" => $userId], false, false);
        array_unshift($playClassData, ["id" => 0, "name" => "稍后观看", "num" => PlayListModel::query()->where(["class_id" => 0, "user_id" => $userId])->count()],
            ["id" => -1, "name" => "我的收藏", "num" => PlayListModel::query()->where(["class_id" => -1, "user_id" => $userId])->count()]);
        foreach ($playClassData as &$item){
            $item["imgUrl"] = "";
            $data = PlayListModel::from("up_play_list as pl")->leftJoin("up_vod_video as v", "v.id", "=", "pl.video_id")
                ->where(["pl.class_id" => $item["id"], "pl.mall_id" => $request->mallData["id"]])
                ->select(["v.cover_img_id"])->orderBy("pl.create_time", "desc")
                ->first();
            if(!empty($data)){
                $data = VodVideoModel::transferField($data->toArray());
                $item["imgUrl"] = $data["coverImgUrl"];
            }
        }
        $this->returnData["data"] = $playClassData;
        return $this->return_result($this->returnData);
    }

    // 我的所有播放列表
    public function getAllPlayClass(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $playClassData = PlayClassModel::getFields("id,name", ["user_id" => $request->userLoginData["id"]], false, false);
        array_unshift($playClassData, ["id" => 0, "name" => "稍后观看"], ["id" => -1, "name" => "我的收藏"]);
        $this->returnData["data"] = $playClassData;
        return $this->return_result($this->returnData);
    }

    // 收藏视频和稍后观看视频
    public function playToCollectVideo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->videoId){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        $classId = isset($request->classId) ? $request->classId : 0;
        if(!VodVideoModel::query()->where("id", $request->videoId)->count()){
            return $this->return_result(ErrorCode::code("customized", "视频不存在"));
        }
        $data = PlayListModel::getFields("id", ["user_id" => $request->userLoginData["id"], "video_id" => $request->videoId, "class_id" => $classId]);
        if($data){
            return $this->return_result(ErrorCode::code("customized", "视频已经存在于列表"));
        }
        PlayListModel::toAdd(["user_id" => $request->userLoginData["id"], "video_id" => $request->videoId, "class_id" => $classId]);
        return $this->return_result($this->returnData);
    }

    // 移除视频
    public function playToRemoveVideo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->videoId){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        $classId = isset($request->classId) ? $request->classId : 0;
        $data = PlayListModel::getFields("id,class_id,video_id", ["user_id" => $request->userLoginData["id"], "video_id" => $request->videoId, "class_id" => $classId]);
        if($data){
            PlayListModel::delById($data["id"], $data);
        }
        return $this->return_result($this->returnData);
    }

    // 我的视频播放列表
    public function getPlayVideoList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $filter = ["pl.user_id" => $request->userLoginData["id"]];
        $filter["pl.class_id"] = $request->classId ?: 0;
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 20;
        $db = PlayListModel::query()->from("up_play_list as pl")->leftJoin("up_vod_video as v", "v.id", "=", "pl.video_id")->where($filter)
            ->select(["v.id","v.title","v.cover_img_id","v.desc","v.view_count","v.video_length", 'v.broadcaster_id',"v.create_time", "v.file_type"]);
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data['list'] = $db->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("pl.create_time", "desc")->get();
        if($data['list']){
            $data['list'] = VodVideoModel::transferField($data['list']->toArray());
            foreach ($data["list"] as &$item){
                $item["commentCount"] = CommentModel::getCount(["belong_id" => $item["id"], "type" => 1, "status" => 1, "mall_id" => $request->mallData["id"]]) +
                    ReplyModel::query()->from(ReplyModel::query()->getModel()->getTable(). " as r")
                        ->leftJoin(CommentModel::query()->getModel()->getTable()." as c", "c.id", '=', "r.comment_id")
                        ->where(["c.belong_id" => $item["id"], "r.status" => 1])
                        ->count();
                $item["createTime"] = UpTools::handleTimeToText($item["createTime"]);
            }
        }
        if($request->classId) {
            $info = PlayClassModel::getFields("user_id,create_time", ["id" => $request->classId]);
        }else{
            $userData = VideoUserModel::getFields("nickname,register_time", ["id" => $request->userLoginData["id"]]);
            $info = ["createTime" => $userData["registerTime"], "userName" => $userData["nickname"]];
        }
        $data["info"] = ["createTime" => !empty($info["createTime"]) ? $info["createTime"] : "", "founder" => !empty($info["userName"]) ? $info["userName"] : ""];
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 我的最近播放列表
    public function getMyRecentlyPlayList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 20;
        $db = PlayedRecordModel::from("up_played_record as pr")->leftJoin("up_vod_video as v", "v.id", "=", "pr.video_id")
            ->where(["pr.user_id" => $request->userLoginData["id"], "v.mall_id" => $request->mallData["id"]])
            ->select(["v.id","v.title","v.cover_img_id","v.desc","v.view_count","v.video_length", 'v.broadcaster_id', "pr.create_time", "v.file_type"]);
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data['list'] = $db->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("pr.create_time", "desc")->get();
        if($data['list']){
            $data['list'] = VodVideoModel::transferField($data['list']->toArray());
            $data["yesterdayCount"] = PlayedRecordModel::query()->whereBetween("create_time", [mktime(0,0,0,date('m'),date('d')-1,date('Y')), mktime(0,0,0,date('m'),date('d'),date('Y'))-1])
                ->where("user_id", $request->userLoginData["id"])->count();
            $data["todayCount"] = PlayedRecordModel::query()->where("create_time", ">=", mktime(0,0,0,date('m'),date('d'),date('Y')))
                ->where("user_id", $request->userLoginData["id"])->count();
            foreach ($data['list'] as $k => &$item){
                $item["name"] = isset($item["broadcasterName"]) ? $item["broadcasterName"] : '';
                if(date("Y-m-d")." 00:00:00" > $item["createTime"]){
                    if(!isset($data["todayCount"])) {
                        $data["todayCount"] = $k;
                    }
                    if(date("Y-m-d", time()-86400)." 00:00:00" > $item["createTime"]){
                        if(!isset($data["yesterdayCount"])) {
                            $data["yesterdayCount"] = $k - $data["todayCount"];
                        }
                    }
                }
            }
            $data["earlierCount"] = $data["count"] - $data["yesterdayCount"] - $data["todayCount"];
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 我的订阅列表
    public function getMySubscribeList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 20;
        $db = SubscriptionModel::from("up_subscription as s")->leftJoin("up_broadcaster as b", "b.id", "=", "s.broadcaster_id")
            ->where(["s.user_id" => $request->userLoginData["id"], "s.mall_id" => $request->mallData["id"]])
            ->select(["b.id", "b.name", "b.avatar_id", "b.desc", "s.remind_status", "b.fan_number"]);
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data['list'] = $db->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("s.create_time", "desc")->get();
        if($data['list']){
            $data['list'] = BroadcasterModel::transferField($data['list']->toArray());
            foreach ($data["list"] as &$item){
                $item["subscribe"] = 1;
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 赞视频
    public function toPraiseVideo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        if (empty(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 1]))) { // 没赞
            OperateModeModel::toAdd(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 1]);
            if(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 2])){ // 有踩
                OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 2]);
            }
        } else {
            OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 1]);
        }
        return $this->return_result($this->returnData);
    }

    // 踩视频
    public function toTreadVideo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频ID"));
        }
        if (empty(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 2]))) { // 没踩
            OperateModeModel::toAdd(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 2]);
            if(OperateModeModel::getCount(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 1])){ // 踩了就要去除赞
                OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 1]);
            }
        } else {
            OperateModeModel::del(["user_id" => $request->userLoginData["id"], "belong_id" => $request->id, "type" => 4, "mode" => 2]);
        }
        return $this->return_result($this->returnData);
    }
}